package com.woyou.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.citaq.ideliver.R;
import com.woyou.bean.ChosenGoods;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.Gift;
import com.woyou.bean.Goods;
import com.woyou.bean.IChoose;
import com.woyou.bean.ShopDetail;
import com.woyou.bean.ShoppingCarService;
import com.woyou.bean.ShoppingCarTitle;
import com.woyou.ui.component.SuperUI;
import com.woyou.ui.fragment.ShopInfoMenuLayout.LayoutControl;
import com.woyou.ui.view.SuperLayout;
import com.woyou.utils.Configure;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.UIUtils;
import com.woyou.utils.eventbus.EventClearShoppingCar;
import com.woyou.utils.eventbus.EventGiftListChange;
import com.woyou.utils.eventbus.EventRefPrice;
import com.woyou.utils.eventbus.EventRestShoppingCarData;
import com.woyou.utils.eventbus.EventShoppingCarChange;

import de.greenrobot.event.EventBus;

@EViewGroup(R.layout.include_shoppingcar)
public class ShoppingCarLayout extends SuperLayout {
	
	private static final String TAG = "ShoppingCarLayout";
	
	// 购物车
	@ViewById RelativeLayout include_shoppingcar_view;
	@ViewById RelativeLayout include_shoppingcar_clear;
	@ViewById ListView include_shoppingcar_lv;
	public ShoppingCarAdapter shoppingCarAdapter;
	private List<Object> shoppingCarData = new ArrayList<Object>();
	private ShopDetail shopDetail;
	private int MAX_HEIGHT;

	public ShoppingCarLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		EventBus.getDefault().register(this);
		int height = Configure.screenHeight;  //得到高度
		MAX_HEIGHT = height - (int)mContext.getResources().getDimension(R.dimen.dp650);
	}
	
	private void findView() {
//		include_shoppingcar_view=(RelativeLayout)findViewById(R.id.include_shoppingcar_view);
//		include_shoppingcar_clear = (RelativeLayout) findViewById(R.id.include_shoppingcar_clear);
		include_shoppingcar_view.setOnClickListener(this);
		include_shoppingcar_clear.setOnClickListener(this);
//		include_shoppingcar_lv = (ListView) findViewById(R.id.include_shoppingcar_lv);
		
	}

	public void setShopDetail(ShopDetail detail){
		this.shopDetail = detail;
	}
	
	@AfterViews
	public void initView() {
		findView();
//		initShoppingCarData();
	}
	
	/**
	 * 清空购物车
	 */
	public void onEvent(EventClearShoppingCar event){
		clearShoppingCar();
	}
	/**
	 * 刷新购物车赠品列表
	 * @param event
	 */
	public void onEvent(EventGiftListChange event){
		
	}
	
	/**
	 * 重构购物车数据
	 * @param event
	 */
	public void onEvent(EventRestShoppingCarData event){
		restShoppingCarData();
	}
	
	
	/**
	 * 初始化购物车
	 */
	@UiThread
	void restShoppingCarData() {
		shoppingCarData.clear();
		
		// 获取购物车列表
		List<IChoose> list = mShoppingCarModel.getChosenGoodsList();
		shoppingCarData.addAll(list);
		
		CodeListResult<Gift> result = mActivitiesModel.getResult();
		if(result!=null&& 1 == result.code ){
			ShoppingCarTitle title=new ShoppingCarTitle();
			title.setTitle("优惠活动");
			shoppingCarData.add(title);
			for( Gift g : result.getList() ){
				Integer giftNum = mActivitiesModel.getGiftNum(g.getaId());
				if( giftNum == null ){
					giftNum = 0;
				}
				g.setQty(giftNum);
				shoppingCarData.add(g);
			}
		}
		
		if(shopDetail!=null){
			ShoppingCarTitle title = null;
			if(shopDetail.getSendFee()>0){
				title=new ShoppingCarTitle();
				title.setTitle("服务费");
				shoppingCarData.add(title);
				
				ShoppingCarService service=new ShoppingCarService();
				service.setName("外送费");
				service.setPrice(""+ParseUtils.String2Money(shopDetail.getSendFee()));
				shoppingCarData.add(service);
			}
			if(shopDetail.getMealsBoxFee()>0&&shopDetail.getMealsBoxFeeType()!=0){
				if(title==null){
					title=new ShoppingCarTitle();
					title.setTitle("服务费");
					shoppingCarData.add(title);
				}
				ShoppingCarService service1=new ShoppingCarService();
				service1.setName("餐盒费");
				service1.setPrice(""+ParseUtils.String2Money(mShoppingCarModel.getMealsBoxFee()));
				shoppingCarData.add(service1);
			}
		}
		
		
		if( shoppingCarAdapter == null ){
			shoppingCarAdapter = new ShoppingCarAdapter(getContext(),shoppingCarData,this);
			include_shoppingcar_lv.setAdapter(shoppingCarAdapter);
		}else{
			shoppingCarAdapter.notifyDataSetChanged(); 
		}
		try {
			UIUtils.setListViewHeightBasedOnChildren(include_shoppingcar_lv, MAX_HEIGHT);
		} catch (Exception e) {
			Log.i(TAG, "动态设置listview高度失败");
			
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.include_shoppingcar_view:
			hide();
			break;
		case R.id.include_shoppingcar_clear:
			//点击清空购物车弹出一个确认清空购物车的dialog
			SuperUI.openBottomDialog(getContext(), "确认要清空购物篮吗？", "", new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					SuperUI.dismiss();
					
				}
			}, "", new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					clearShoppingCar();
					SuperUI.dismiss();
					
				}
			});
			break;
		}
	}
	
	/**
	 * 清空购物车
	 */
	public void clearShoppingCar(){
		mShoppingCarModel.clearShopppingCar(); 
		hide();
	}
	
	/**
	 * 防止View的事件穿透
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}
	
	/**
	 * 隐藏
	 */
	public void hide(){
		setVisibility(View.GONE);
		EventBus.getDefault().post(new EventShoppingCarChange());
		EventBus.getDefault().post(new EventRefPrice());
	}
	
	/**
	 * 显示
	 */
	public void show(){
		_show();
		mShoppingCarModel.setShopDetail(shopDetail);
		restShoppingCarData();
//		checkGiftList();
	}
	
	private void _show(){
		setVisibility(View.VISIBLE);
	}

	public class ShoppingCarAdapter extends BaseAdapter implements OnClickListener {

		private static final String TAG = "ShoppingCarAdapter";
		
		private Context context;
		private List<Object> data = new ArrayList<Object>();
		private ShoppingCarLayout layout;
		
		public ShoppingCarAdapter(Context context, List<Object> data,ShoppingCarLayout layout) {
			this.context = context;
			this.data = data;
			this.layout=layout;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		int count = 0;
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.i(TAG, "getView count="+count+" position="+position );
			count++;
			ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.item_shoppingcar_lv, null);
				//商品 
				viewHolder.goods_view = (RelativeLayout) convertView.findViewById(R.id.item_goods_view);
				viewHolder.goods_name = (TextView) convertView.findViewById(R.id.item_goods_name);
				viewHolder.goods_price = (TextView) convertView.findViewById(R.id.item_goods_price);
				viewHolder.goods_add = (ImageView) convertView.findViewById(R.id.item_goods_add);
				viewHolder.goods_num = (TextView) convertView.findViewById(R.id.item_goods_num);
				viewHolder.goods_minus = (ImageView) convertView.findViewById(R.id.item_goods_minus);
				viewHolder.goods_adjust=(LinearLayout)convertView.findViewById(R.id.item_goods_adjust);
				viewHolder.goods_prop = (TextView) convertView.findViewById(R.id.item_goods_prop);
				//title
				viewHolder.title_view=(RelativeLayout)convertView.findViewById(R.id.item_title_view);
				viewHolder.title_name=(TextView)convertView.findViewById(R.id.item_title_name);
				//服务费
				viewHolder.service_view=(RelativeLayout)convertView.findViewById(R.id.item_service_view);
				viewHolder.service_name=(TextView)convertView.findViewById(R.id.item_service_name);
				viewHolder.service_fee=(TextView)convertView.findViewById(R.id.item_service_fee);
				convertView.setTag(viewHolder);
				viewHolder.goods_adjust.setOnClickListener(this);
				viewHolder.goods_add.setOnClickListener(this);
				viewHolder.goods_minus.setOnClickListener(this);
				
				viewHolder.goods_adjust.setTag(viewHolder);
				viewHolder.goods_add.setTag(viewHolder);
				viewHolder.goods_minus.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			viewHolder.goods_view.setVisibility(View.GONE);
			viewHolder.title_view.setVisibility(View.GONE);
			viewHolder.service_view.setVisibility(View.GONE);
			
			Object obj = data.get(position);
			if (obj instanceof IChoose) {
				viewHolder.goods_view.setVisibility(View.VISIBLE);
				// 商品
				IChoose chosenGoods = (IChoose) obj;
				viewHolder.gift = null;
				viewHolder.chosenGoods = chosenGoods;
				viewHolder.goods_name.setText(chosenGoods.getgName());
				viewHolder.goods_price.setText(Html.fromHtml("<small>￥</small>"+ ParseUtils.formatPrice(viewHolder.chosenGoods.getPrice()) +"<small>/"+chosenGoods.getUnit()+"</small>"));
				viewHolder.goods_add.setVisibility(View.VISIBLE);
				viewHolder.goods_num.setVisibility(View.VISIBLE);
				viewHolder.goods_minus.setVisibility(View.VISIBLE);
				refChosenGoodsNum(viewHolder);
				// 判断是否显示属性
					if (mGoodsModel.hasOption(chosenGoods)) {
						viewHolder.goods_adjust.setVisibility(View.VISIBLE);
						mShoppingCarModel.restName(chosenGoods);
						viewHolder.goods_prop.setText(Html.fromHtml(viewHolder.chosenGoods.getNames()));
					} else {
						viewHolder.goods_adjust.setVisibility(View.GONE);
					}
			} else if (obj instanceof ShoppingCarTitle) {
				viewHolder.title_view.setVisibility(View.VISIBLE);
				//title
				ShoppingCarTitle title=(ShoppingCarTitle)obj;
				viewHolder.title_name.setText(""+title.getTitle());
				
			} else if (obj instanceof ShoppingCarService) {
				viewHolder.service_view.setVisibility(View.VISIBLE);
				//服务费
				ShoppingCarService service=(ShoppingCarService)obj;
				viewHolder.service_name.setText(""+service.getName());
				viewHolder.service_fee.setText(Html.fromHtml("<small>￥</small>"+service.getPrice()));
			}else if( obj instanceof Gift ){
				//赠品
				Gift gift = (Gift) obj;
				onGiftItem(viewHolder, gift);
			}

			return convertView;
		}

		private void onGiftItem(ViewHolder viewHolder, Gift gift) {
			viewHolder.chosenGoods = null;
			viewHolder.gift = gift;
			viewHolder.goods_view.setVisibility(View.VISIBLE);
			viewHolder.goods_adjust.setVisibility(View.GONE);
			
			if(gift.getPrice()<=0){
				viewHolder.goods_add.setVisibility(View.INVISIBLE);
				viewHolder.goods_num.setVisibility(View.VISIBLE);
				viewHolder.goods_minus.setVisibility(View.INVISIBLE);
			}else{
				Integer giftNum = mActivitiesModel.getGiftNum(viewHolder.gift.getaId());
				if( giftNum == 0 ){
					viewHolder.goods_add.setVisibility(View.VISIBLE);
					viewHolder.goods_num.setVisibility(View.INVISIBLE);
					viewHolder.goods_minus.setVisibility(View.INVISIBLE);
				}else{
					viewHolder.goods_add.setVisibility(View.VISIBLE);
					viewHolder.goods_num.setVisibility(View.VISIBLE);
					viewHolder.goods_minus.setVisibility(View.VISIBLE);
				}
				
			}
			String unit = "";
			if( viewHolder.gift.getPrice() <0 ){
				unit = "-￥"+ParseUtils.formatPrice(Math.abs(viewHolder.gift.getPrice()));
				viewHolder.gift.setQty(viewHolder.gift.getMaxQty());
				viewHolder.goods_price.setText(unit);
				viewHolder.goods_num.setText("");
				viewHolder.goods_name.setText(gift.getaName());
			}else if( viewHolder.gift.getPrice() > 0 ){
				unit = "/"+viewHolder.gift.getUnit();
				viewHolder.goods_price.setText(Html.fromHtml("<small>￥</small>"+ ParseUtils.formatPrice(viewHolder.gift.getPrice()) +"<small>"+unit+"</small>"));
				viewHolder.goods_num.setText(viewHolder.gift.getQty()+"");
				viewHolder.goods_name.setText(gift.getaName());
			}else if( viewHolder.gift.getPrice() == 0 ){
				viewHolder.gift.setQty(viewHolder.gift.getMaxQty());
				viewHolder.goods_price.setText("赠送");
				viewHolder.goods_num.setText(viewHolder.gift.getQty()+"");
				viewHolder.goods_name.setText(gift.getaName());
			}

		}

		/**
		 * 加减号被点击时调用 设置数量
		 * @param viewHolder
		 */
		private void refChosenGoodsNum(ViewHolder viewHolder) {
			if(viewHolder.chosenGoods.getChosenNum()>0){
				viewHolder.goods_num.setText(viewHolder.chosenGoods.getChosenNum() + "");
			}else{
				viewHolder.goods_num.setVisibility(View.GONE);
				viewHolder.goods_minus.setVisibility(View.GONE);
			}
		}



		@Override
		public void onClick(View v) {
			ViewHolder viewHolder;
			Goods parent;
			IChoose cg;
			switch (v.getId()) {
			case R.id.item_goods_adjust:
				viewHolder = (ViewHolder) v.getTag();
				// 向购物车添加数据
				cg = viewHolder.chosenGoods;
				parent = ((ChosenGoods)cg).getParent();
				//显示已选好的商品属性
				mLayoutControl.showPropView(parent, (ChosenGoods)cg);
				break;
			case R.id.item_goods_add:
				viewHolder = (ViewHolder) v.getTag();
				if( viewHolder.chosenGoods != null ){
					goodsAddClick(viewHolder);
				}else{
					giftAddClick(viewHolder);
				}
			
				break;
			case R.id.item_goods_minus:
				viewHolder = (ViewHolder) v.getTag();
				if( viewHolder.chosenGoods != null ){
					goodsMinusClick(viewHolder);
				}else{
					giftMinusClick(viewHolder);
				}
			
				break;
			default:
				break;
			}
		}

		//增加一个赠品
		private void giftAddClick(ViewHolder viewHolder) {
			Gift gift = viewHolder.gift;
			TextView number = (TextView) viewHolder.goods_num;
			int pieces = gift.getQty();
			
			if( pieces >= gift.getMaxQty() ){//已经达到最大数量,不做任何操作
				Toast.makeText(context, "不能再多了", 0).show();
				return;
			}
			++pieces;
			number.setText(pieces + "");
			gift.setQty(pieces);
			viewHolder.goods_num.setVisibility(View.VISIBLE);
			viewHolder.goods_minus.setVisibility(View.VISIBLE);
			mActivitiesModel.putGiftNum(gift.getaId(), gift.getQty());
			mShoppingCarModel.calculate();
			EventBus.getDefault().post(new EventGiftListChange());
		}
		
		//减去一个赠品
		private void giftMinusClick(ViewHolder viewHolder){
			Gift gift = viewHolder.gift;
			TextView number = (TextView) viewHolder.goods_num;
			int pieces = gift.getQty();
			if (pieces > 0) {
				--pieces;
			}
			if( pieces == 0 ){
				//等于0 不做任何操作
				viewHolder.goods_num.setVisibility(View.INVISIBLE);
				viewHolder.goods_minus.setVisibility(View.INVISIBLE);
			}
			number.setText(pieces + "");
			gift.setQty(pieces);

			mActivitiesModel.putGiftNum(gift.getaId(), gift.getQty());
			mShoppingCarModel.calculate();
			EventBus.getDefault().post(new EventGiftListChange());
		}

		private void goodsAddClick(ViewHolder viewHolder) {
			IChoose cg;
			// 向购物车添加数据
			cg = viewHolder.chosenGoods;
			
			mShoppingCarModel.addGoods(cg);
			EventBus.getDefault().post(new EventRefPrice());
			refChosenGoodsNum(viewHolder);
			//TODO 有赠品时需要刷新 购物车
			mLayoutControl.checkGiftList();
			if(shopDetail.getMealsBoxFeeType()==2){
				restShoppingCarData();
			}
		}

		private void goodsMinusClick(ViewHolder viewHolder) {
			IChoose cg;
			// 向购物车删减数据
			cg = viewHolder.chosenGoods;
			mShoppingCarModel.minusGoods(cg);
			//判断是否购物车还有商品如果没有隐藏购物车
			int size = mShoppingCarModel.getChosenGoodsList().size();
			if( cg.getChosenNum() == 0 ){
				EventBus.getDefault().post(new EventRestShoppingCarData());
			}else{
				refChosenGoodsNum(viewHolder);
			}
			if(size==0){
				layout.hide();
			}
			EventBus.getDefault().post(new EventRefPrice());
			//TODO 有赠品时需要刷新 购物车
			mLayoutControl.checkGiftList();
			if(shopDetail.getMealsBoxFeeType()==2){
				restShoppingCarData();
			}
		}
		
		@Override
		public void notifyDataSetChanged() {
			count = 0;
			Log.i(TAG, "notifyDataSetChanged");
			super.notifyDataSetChanged();
		}
		
	}
	
	private LayoutControl mLayoutControl;
	public void setLayoutControl(LayoutControl control){
		this.mLayoutControl = control;
	}
	
	static class ViewHolder {
		// 商品
		RelativeLayout goods_view;
		TextView goods_name;
		TextView goods_price;
		ImageView goods_add;
		TextView goods_num;
		ImageView goods_minus;
		LinearLayout goods_adjust;
		TextView goods_prop;
		// titile
		RelativeLayout title_view;
		TextView title_name;
		// 服务费
		RelativeLayout service_view;
		TextView service_name;
		TextView service_fee;
//		Goods goods;
		IChoose chosenGoods;
		Gift gift;
	}
}
